import React, {
  FC,
  ReactElement,
  useCallback,
  useEffect,
  useReducer,
} from "react";
import { Itodo, IState, ACTION_TYPE } from "./typings";
import TdInput from "./input";
import TdList from "./List";
// import axios from "axios";
import { todoReducer } from "./reducer";
 import "./style.css";

// const initalState: IState = {
//   todoList: [
//     {
//       id: 1,
//       content: "item1",
//       completed: false,
//     },
//   ],
// };

function init(initTodolist: Itodo[]): IState {
  return {
    todoList: initTodolist,
  };
}

const TodoList: FC = (): ReactElement => {
  // const [todoList, setTodoList] = useState<Itodo[]>([
  //   {
  //     id: 1,
  //     content: "item1",
  //     completed: false
  //   }
  // ]);

  const [state, dispatch] = useReducer(todoReducer, [], init);

  /*useEffect第二个参数，也可以传入值。当如果有值的时候，那useEffect会在这些值更新的时候触发
   如果只是个空数组，则只会在didMounts的时候触发。*/
  useEffect(() => {
    const todolist = JSON.parse(
      window.localStorage.getItem("todolist") || "[]"
    );
    dispatch({
      type: ACTION_TYPE.INIT_TODO,
      payload: todolist,
    });
    
  }, []);

  useEffect(() => {
    window.localStorage.setItem("todolist", JSON.stringify(state.todoList));
  }, [state.todoList]);

  const addTodo = useCallback((todo: Itodo) => {
    //  setTodoList(todoList => [...todoList, todo]);
    dispatch({
      type: ACTION_TYPE.ADD_TODO,
      payload: todo,
    });

  }, []);

  const removeTodo = useCallback((id: number) => {
    //  setTodoList(todoList => [...todoList, todo]);
    dispatch({
      type: ACTION_TYPE.REMOVE_TODO,
      payload: id,
    });
  }, []);

  const toggleTodo = useCallback((id: number) => {
    //  setTodoList(todoList => [...todoList, todo]);
    dispatch({
      type: ACTION_TYPE.TOGGLE_TODO,
      payload: id,
    });
  }, []);

  return (
    <div className='todo_list'>
      <TdInput addTodos={addTodo} todoList={state.todoList} />
      <TdList
        todoList={state.todoList}
        removeTodo={removeTodo}
        toggleTodo={toggleTodo}
      />
    </div>
  );
};
export default TodoList;
